/*
 * Copyright (c) 2006 - 2022, webrx.cn All rights reserved.
 *
 */
package cn.webrx;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>Project: app2022 - T18
 * <p>Powered by webrx On 2022-02-07 14:34:05
 *
 * @author webrx [webrx@126.com]
 * @version 1.0
 * @since 17
 */
public class T18 {
    Object b = new Object();
    List<String> list = new ArrayList<>();

    public static void main(String[] args) {
        var t = new T18();
        new Thread(t::work, "T1").start();
        new Thread(t::work, "T2").start();
        new Thread(t::work, "T3").start();
        new Thread(t::count, "统计").start();
    }

    void work() {
        String tn = Thread.currentThread().getName();
        System.out.println(tn + "线程启动");
        try {
            TimeUnit.MILLISECONDS.sleep(5);
        } catch (Exception e) {
            e.printStackTrace();
        }
        while (true) {
            synchronized (this) {
                synchronized (b) {
                    try {
                        TimeUnit.SECONDS.sleep(1);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    String ok = tn + ":item" + (list.size() + 1);
                    System.out.println(ok);
                    list.add(ok);
                    if (list.size() == 15) {
                        try {
                            b.notifyAll();//唤醒其它线程，不释放当前占用的锁
                            b.wait();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }

    void count() {
        String tn = Thread.currentThread().getName();
        System.out.println(tn + "线程启动");

        synchronized (b) {
            try {
                System.out.println("监控中...");
                b.wait();//当前线程阻塞状态，让出CPU执行权，不会自动唤醒
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("统计提示：已经到15个元素。");
            b.notify();
        }
    }
}
